import React, { useEffect, useState } from 'react'
import { Table, Tag, Space, Button, Form, Input, Select, message } from 'antd'
import { fetchAddItem, fetchDeleteItem, fetchUpdateItem, fetchList } from '../../api'

import arrTest from '../../mock/data.json'
import MyModal from './components/Modal'
import SearchBar from './components/SearchBar'
import TableList from './components/TableList'
import MyPagination from './components/MyPagination'
import withRouter from '../../utils/withRouter'

// table: columns决定你渲染哪个字段
const Home = () => {
  // 保存数据
  const [tableList, setTableList] = useState([])
  // 存储国家性质数组
  const [natureArr, setNatureArr] = useState([])
  // 控制显示弹出框状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 状态，判断 是编辑弹出框 还是新增弹出框
  const [popType, setPoyType] = useState('')
  // 状态 保存编辑数据
  const [editData, setEditData] = useState({})

  // 分页状态
  const [current, setCurrent] = useState(1)
  const [size, setSize] = useState(5)
  const [total, setTotal] = useState(0)

  // table表头
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '国家',
      dataIndex: 'countryName',
      key: 'countryName',
    },
    {
      title: '所属大洲',
      dataIndex: 'continent',
      key: 'continent',
    },
    {
      title: '国家性质',
      dataIndex: 'nature',
      key: 'nature',
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (tags) => {
        return (
          <>
            <Tag color={tags % 2 ? 'geekblue' : 'green'} key={tags}>
              {tags % 2 ? '友好国家' : '非友好国家'}
            </Tag>
          </>
        )
      },
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              // 编辑调用弹出框
              setIsModalVisible(true)
              setPoyType('edit')
              setEditData(record)
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              const { id } = record
              fetchDeleteItem({ id }).then((res) => {
                getList({})
              })
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ]

  useEffect(() => {
    getList({ page: current, size })
  }, [current, size])

  // 初始化请求数据
  const getList = async ({ page, size }) => {
    const response = await fetchList({ page, size })
    console.log('response:', response)
    // 总条数
    setTotal(response.data.total)

    setNatureArr(response.data.natureArr)
    response.data.children.forEach((item) => {
      item.tags = item.id
      item.key = item.id
      item.time = Date.now()
    })
    // console.log(response.data, 'response.data')
    setTableList(response.data.children)
  }

  // 新增按钮 ： 控制弹出框显示隐藏
  const showModal = () => {
    setPoyType('add')
    // 显示弹出框
    setIsModalVisible(true)
  }

  // 弹出框的确认按钮
  const handleOk = async (data) => {
    if (popType === 'add') {
      // 新增接口
      const AddData = await fetchAddItem(data)
    } else {
      // 编辑接口
      console.log('data:', { ...editData, ...data })
      const dataE = await fetchUpdateItem({ ...editData, ...data })
    }
    // 请求完接口之后，重新渲染数据
    getList({})
    // 关闭弹出框
    setIsModalVisible(false)
  }

  // 弹出框的取消按钮
  const handleCancel = () => {
    setIsModalVisible(false)
  }

  // 搜索函数
  const onFinish = (values) => {
    if (values.countryName && values.continent && values.nature) {
      const arr = arrTest.children.filter((v) => {
        if (v.countryName === values.countryName && v.continent === values.continent && v.nature === values.nature) {
          return v
        } else {
          return null
        }
      })
      arr.length &&
        arr.forEach((item) => {
          item.tags = item.id
          item.key = item.id
          item.time = Date.now()
        })
      // return arr
      setTableList(arr)
    } else {
      message.error('请先填写或者选中内容')
    }
  }

  // 重置按钮
  const handleResetClick = () => {
    getList({})
  }

  return (
    <div>
      {/* 搜索组件 */}
      <SearchBar onFinish={onFinish} handleResetClick={handleResetClick}></SearchBar>
      {/* 弹出框组件 */}
      <MyModal
        editData={editData}
        isModalVisible={isModalVisible}
        popType={popType}
        natureArr={natureArr}
        handleOk={handleOk}
        handleCancel={handleCancel}
      ></MyModal>
      {/* 新增调用弹出框 点击调用新增弹出框的时候，要清空数据 */}

      <TableList showModal={showModal} tableList={tableList} columns={columns} />

      <MyPagination
        onChange={(page, size) => {
          console.log(page, size, '--------')
          setCurrent(page)
        }}
        onShowSizeChange={(current, size) => {
          setSize(size)
        }}
        current={current}
        size={size}
        total={total}
      ></MyPagination>
    </div>
  )
}

export default withRouter(Home)
